package com.zlx.mall.basic.web.configuration;

import org.hibernate.validator.BaseHibernateValidatorConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.validation.MessageInterpolatorFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;

import javax.annotation.Resource;
import java.util.Properties;

/**
 * @author qingke
 * @see org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration
 **/
@Configuration
@AutoConfigureBefore(value = {WebMvcConfiguration.class})
public class I18nValidatorConfiguration {

    @Resource
    private MessageSource messageSource;

    @Bean
    public LocalValidatorFactoryBean validator(ApplicationContext applicationContext) {
        Properties properties = new Properties();
        properties.setProperty(BaseHibernateValidatorConfiguration.FAIL_FAST, Boolean.TRUE.toString());

        LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
        bean.setValidationProperties(properties);
        bean.setValidationMessageSource(messageSource);
        MessageInterpolatorFactory interpolatorFactory = new MessageInterpolatorFactory(applicationContext);
        bean.setMessageInterpolator(interpolatorFactory.getObject());
        return bean;
    }

    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor(ApplicationContext applicationContext) {
        MethodValidationPostProcessor processor = new MethodValidationPostProcessor();
        processor.setValidator(validator(applicationContext));

        boolean proxyTargetClass = applicationContext.getEnvironment().getProperty("spring.aop.proxy-target-class", Boolean.class, true);
        processor.setProxyTargetClass(proxyTargetClass);
        return processor;
    }
}
